/**
 * https://wrist.blog.csdn.net/article/details/132722238?spm=1001.2014.3001.5502
 * */
const { WechatyBuilder } = require('wechaty');
const qrcode = require('qrcode-terminal');
const fs = require('fs');
const FormData = require('form-data')
const axios = require('axios');
let Duplex = require('stream').Duplex;


const data = fs.readFileSync('config.json', 'utf8');
const config = JSON.parse(data);
let bot = {}

const apiUrl = 'https://api.aikanshe.com/agency/quanxiWithReport'
const APPKEY = config.appkey;
const token = config.token||"";//puppet_padlocal_xxxxxxxxxxxx

if(token.length > 1){
    const { PuppetPadlocal } = require("wechaty-puppet-padlocal");
    const puppet = new PuppetPadlocal({
        token: token
    });
    bot = WechatyBuilder.build({
        name: "wechaty-puppet-padlocal",
        puppet
    })
}else{
    bot = WechatyBuilder.build({
      name: 'wechat-puppet-wechat', // generate xxxx.memory-card.json and save login data for the next login
    })
}

function wait(ms) {
    return new Promise(resolve =>setTimeout(() =>resolve(), ms));
};
function aikanshe(file,filename,name) {
    
    return new Promise((resolve,reject) => {
        const formData = new FormData();
        formData.append('file', file, file.name || filename);
        formData.append('appkey',APPKEY)
        formData.append('age',16)
        formData.append('male',1)
        formData.append('methodName','quanxi')
        formData.append('frontCamera',0)
        formData.append('name',name||'')
        axios({
            url: apiUrl,
            method:'post',
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            data: formData
        }).then((res) => {
            resolve(res.data)
        }).catch((err) => {
            reject(err)
        });
    })
}




bot.on('scan', (code, status) => {
    qrcode.generate(code, { small: false });
})

bot.on('login', user => console.log(`User ${user} logged in`))

bot.on('message', async message => {
    // if (message.age() > 3 * 60) {
    //     log.info('Bot', 'on(message) skip age("%d") > 3 * 60 seconds: "%s"', message.age(), message)
    //     return
    // }

    const room = message.room()
    const from = message.talker()
    // const text = message.text()

    if (!from) {
       return
    }

    console.log((room ? '[' + room.topic() + ']' : '')
                  + '<' + from.name() + '>'
                  + ':' + message,
    )

    if (message.self()) {
        return // skip self
    }
    
    if (message.type() == bot.Message.Type.Image) {
        const image = await message.toFileBox()
        const ws = await fs.createWriteStream(image._name);  
        await ws.write(image.buffer);  

        await wait(2000);

        const imageStream = await fs.createReadStream(image._name);
        
        if (room) {
            // const isMentionSelf = await message.mentionSelf()
            // console.log('isMentionSelf: ' , isMentionSelf);
            // if(isMentionSelf){
                aikanshe(imageStream,image._name,from.name()).then((res)=>{
                    console.log('检测结果: ' , res);
                    if (res.code == '40001') {
                        let text = ''
                        if(token.length > 1){
                            text = new bot.UrlLink({
                                title: from.name() + "的AI舌诊检测报告，请查收！",
                                description: res.data.typeName,
                                thumbnailUrl: 'https://www.aikanshe.com/static/' + res.data.uploadPath,
                                url: 'https://www.aikanshe.com/static/' +res.data.pdfUrl,
                            });
                        }else{
                            text = from.name() + "的AI舌诊检测报告，请查收:\nhttps://www.aikanshe.com/static/"+ encodeURIComponent(res.data.pdfUrl);//群聊发送消息
                        }
                        
                        room.say(text) ;
                    }

                    
                    
                }, (err)=>{
                    console.log(err)
                });
            // }
            
        }else{
            aikanshe(imageStream,image._name,from.name()).then((res)=>{
                console.log('检测结果: ' , res);
                // const obj = JSON.parse(str)
                let text = "";
                if (res.code == '40001') {
                    let text = from.name() + "的AI舌诊检测报告，请查收:\nhttps://www.aikanshe.com/static/"+ encodeURIComponent(res.data.pdfUrl);
                    rom.say(text);
                }

                f
                
            }, (err)=>{
                console.log(err)
            });
            
        }
        
        
        
        
    }

});

bot.start();

